<?php

//下划线命名到驼峰命名
function toCamelCase($str)
{
    $array = explode('_', $str);
    $result = $array[0];
    $len=count($array);
    if($len>1)
    {
        for($i=1;$i<$len;$i++)
        {
            $result.= ucfirst($array[$i]);
        }
    }
    return ucfirst($result);
}

if (isset($argc)) {
    for ($i = 0; $i < $argc; $i++) {
        echo "Argument #" . $i . " - " . $argv[$i] . "\n";
    }
}
else {
    echo "argc and argv disabled\n";
}

if(empty($argv[1])){
    exit('表名不能为空');
}


// Connect to the database
$conn = new \mysqli("localhost", "root", "123456", "duanju");

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$table = $argv[1];
// Get the table structure
$result = $conn->query("DESCRIBE {$table}");
if (!$result) {
    die("Query failed: " . $conn->error);
}

// Create an empty Eloquent model
$model = new stdClass();
$propterys = [];
while ($row = $result->fetch_assoc()) {
    // Get the column name and data type
    $columnName = $row["Field"];
    $columnType = $row["Type"];
    $model->$columnName = null;
    $propterys[] = " * @property mixed $"."{$columnName}";
    $model->$columnName = function ($value = null) use ($columnName) {
        if (is_null($value)) {
            return $this->$columnName;
        } else {
            $this->$columnName = $value;
        }
    };
}
$model = (object) get_object_vars($model);
$modelname=toCamelCase($table);
//$modelname =str_replace('s','' , toCamelCase($table)); ;
$tmp = file_get_contents('./model/Test.tpl');
$a = str_replace('{{modelname}}',$modelname , $tmp);
$a = str_replace('{{tableName}}', $table, $a);

$pro_str = implode("\n",$propterys);
$a = str_replace('{{proptertys}}', $pro_str, $a);
$create_file =  './model/'.toCamelCase($table).'.php';

echo $create_file;
if (!file_exists($create_file)) {
    // 创建文件
    touch($create_file);
    echo "文件创建成功！";
} else {
    echo "文件已存在！替换内容";
}
file_put_contents($create_file, $a);

